package SortAlgorithm;

import org.reflections.Reflections;

import java.util.*;

public class 速度测试 {

    public Map<String,Long> map =new HashMap<>();
    private int[] validArr;

    public int[] getRandomArr(int length){

        Random random=new Random();
        int[] result=new int[length];

        for (int i = 0; i < length; i++) {
            result[i]=random.nextInt(length);
        }
        this.validArr=Arrays.copyOf(result, result.length);
        Arrays.sort(this.validArr);
        return result;
    }

    public void testTime(ISort sortMethod,int[] arr){
        int[] copyArr = Arrays.copyOf(arr, arr.length);//底层用的就是System.copy
        long startTime=System.currentTimeMillis();
        sortMethod.sort(copyArr);
        if(!Arrays.equals(copyArr,validArr)){
            throw new RuntimeException(sortMethod.getClass().getSimpleName()+"方法出错");
        }
        map.put(sortMethod.getClass().getSimpleName(),(System.currentTimeMillis()-startTime));
    }

    public void printResult(){
        System.out.println("当前测试容量:"+this.validArr.length);
        PriorityQueue<Map.Entry<String,Long>> priorityQueue=new PriorityQueue<>((o1, o2) -> (int) (o1.getValue()-o2.getValue()));
        priorityQueue.addAll(map.entrySet());
        while (!priorityQueue.isEmpty()){
            Map.Entry<String, Long> poll = priorityQueue.poll();
            System.out.println(poll.getKey()+"方法,耗费时间:"+poll.getValue()+"毫秒");
        }
    }

    public static void main(String[] args) {
        速度测试 n=new 速度测试();
        int[] arr = n.getRandomArr(90000);
        // 需要外部Reflections依赖
        Reflections reflection=new Reflections(速度测试.class.getPackage().getName());
        Set<Class<? extends ISort>> set=reflection.getSubTypesOf(ISort.class);
        List<ISort> instanceList=new ArrayList<>();
        for (Class<? extends ISort> aClass : set) {
            try {
                ISort iSort = aClass.newInstance();
                instanceList.add(iSort);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        for (ISort iSort : instanceList) {
            n.testTime(iSort,arr);
        }
        n.printResult();
    }

}
